using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.UI;

public class TipLabels : MonoBehaviour
{
    private readonly float normalPosY = -105f;
    private readonly float prefabSizeY = 50f;

    private LinkedList<KeyValuePair<Transform, bool>> tipChain;
    private Transform tipItemPrefab;

    private void Awake()
    {
        tipChain = new LinkedList<KeyValuePair<Transform, bool>>();
        Loader.Instance.LoadAsyn<Transform>("UI/TipItem", (trs) => { tipItemPrefab = trs; });
    }

    public void ShowTip(string label)
    {
        //ClearDirty();
        Transform spawnTrs = Instantiate<Transform>(tipItemPrefab);
        spawnTrs.SetParent(transform);
        spawnTrs.Reset();
        spawnTrs.GetComponentInChildren<Text>().text = label;
        float originPosY = normalPosY;
        if (tipChain.Count>0)
        {
            var peek = tipChain.Last;
            Transform preTipTrs = peek.Value.Key;
            bool isInside = peek.Value.Value;
            if (isInside)
            {
                originPosY = preTipTrs.localPosition.y + prefabSizeY;
            }
        }
        spawnTrs.localPosition = new Vector3(0, normalPosY, 0);
        tipChain.AddLast(new KeyValuePair<Transform, bool>(spawnTrs, false));
        float distance = 105f - spawnTrs.localPosition.y;
        DOTween.To((t) =>
        {
            float posY = originPosY + distance * t;
            spawnTrs.localPosition = new Vector3(0, posY, 0);
            if (posY > -55f)
            {
                var temp = tipChain.Last;
                temp.Value= new KeyValuePair<Transform, bool>(spawnTrs, false);
            }
        }, 0, 1, 3f).onComplete = () =>
        {
            DestroyImmediate(spawnTrs.gameObject);
        };
    }

    private void ClearDirty()
    {
        using (var e=tipChain.GetEnumerator())
        {
            while (e.MoveNext())
            {
                if (e.Current.Key==null)
                {
                    var kp = e.Current;
                    tipChain.Remove(kp);
                }
            }
        }
    }
}
